__module_name__ = "xchat-paste" 
__module_version__ = "0.1" 
__module_description__ = "Paste long messages to paste bins."
__module_author__ = "Mateusz Bilski mateusz.bilski@gmail.com"

import xchat 
import httplib
import urllib
import re

sended = 0
message = list('')

def paste(message):
	s = "\n"
	params = urllib.urlencode({ 'name': 'bot', 'code_lang': 'Plain Text', 'tab_length': '4', 'code': s.join(message), 'submit': 'submit' } )
	headers = {"Content-type": "application/x-www-form-urlencoded", "Accept": "text/plain"}
	
	conn = httplib.HTTPConnection("www.wklej.org:80")
	conn.request("POST", "/index.php", params, headers)
	
	response = conn.getresponse()
	data = response.read()
	conn.close()
	
	p = re.compile('<a href=.*?id\/([A-Fa-f0-9]{10}?)"')
	return "http://wklej.org/id/" + p.findall( data )[0]
	

def send(userdata):
	global message
	global sended
	if len (message) != 0:
		if len (message) > 2 or len( message ) > 400:
			print "Too long message. Pasting..."
			link = paste(message)
			sended = 1
			xchat.command("msg " + xchat.get_info("channel") + " " + link)	
		else:
			for i in message:
				sended = 1
				xchat.command("msg " + xchat.get_info("channel") + " " + i)	
		message = list('')
	return 1
	
def messageHandler(word, word_eol, userdata): 
	global sended
    	global message
	message.append( word_eol[0] )
    	return xchat.EAT_ALL
 
 
xchat.hook_command("", messageHandler) 
sendHandler = xchat.hook_timer(10, send)
